package com.lemon.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtils {

	private static SqlSessionFactory factory;
	
	static {
		factory = getFactory("mybatis-config.xml", "jdbc.properties");
	}

	/**
	 * 开启一个SqlSession
	 * @return
	 */
	public static SqlSession getSession() {
		if (factory == null) {
			factory = getFactory("mybatis-config.xml", "jdbc.properties");
		}
		
		return factory.openSession();
	}

	/**
	 * 创建SqlSessionFactory
	 * @param mybatisConfig mybatis配置文件名
	 * @param jdbcProp jdbc配置文件名
	 * @return
	 */
	public static SqlSessionFactory getFactory(String mybatisConfig, String jdbcProp) {
		try {
			// 读取mybatis配置文件
			InputStream in = Resources.getResourceAsStream(mybatisConfig);
			// 读取jdbc连接信息配置文件
			Properties prop = Resources.getResourceAsProperties(jdbcProp);
			// 初始化工厂并返回
			return new SqlSessionFactoryBuilder().build(in, prop);
		} catch (IOException e) {
			return null;
		}
	}
}
